package edu.whu.demo.service;

import edu.whu.demo.dao.CommodityRepository;
import edu.whu.demo.entity.Commodity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class CommodityService {
    @Autowired
    private CommodityRepository repository;

    public Commodity addCommodity(Commodity commodity) {
        return repository.saveAndFlush(commodity);
    }

    public Commodity getCommodity(long id) {
        try{
            return repository.findById(id).get();
        }
        catch (Exception e){
            return null;
        }
    }

    public void updateCommodity(long id, Commodity commodity) {
        repository.save(commodity);
    }

    public void deleteCommodity(Long id) {
        repository.deleteById(id);
    }

    public List<Commodity> findCommodities(String name, Double price) {
        Specification specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(name != null) {
                list.add(criteriaBuilder.like(root.get("name"), "%" + name + "%"));
            }
            if(price != null) {
                list.add(criteriaBuilder.le(root.get("price"), price));
            }
            Predicate[] predicates = list.toArray(new Predicate[list.size()]);
            return criteriaBuilder.and(predicates);
        };
        return repository.findAll(specification);
    }

    public List<Commodity> findCommoditiesBySupplier(long id) {
        return repository.findCommoditiesBySupplier(id);
    }

    public void deleteRecordByCommodityId(long id) {
        repository.deleteByCommodityId(id);
    }

    public void addRecord(long commodity_id, long supplier_id){
        repository.insertRecord(commodity_id, supplier_id);
    }
}
